package com.vcc.web.core.queue.batch.unFreeze.queue;

import com.vcc.channel.base.model.response.CardInfoVo;
import com.vcc.channel.base.service.ChannelBaseService;
import com.vcc.core.constant.CardStatusEnum;
import com.vcc.data.entity.UserCard;
import com.vcc.service.service.*;
import com.vcc.web.core.queue.batch.unFreeze.model.UnFreezeQueueDto;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Executors;

@Log4j2
@Component
public class UnFreezeQueue implements CommandLineRunner {

    @Resource
    private UserCardService userCardService;
    @Resource
    private TaskLogService taskLogService;
    @Resource
    private ApplicationContext applicationContext;
    @Resource
    private CardTypeService cardTypeService;
    @Resource
    private UserCardWalletService userCardWalletService;
    @Resource
    private CardOrderService cardOrderService;
    @Resource
    private TaskLogInfoService taskLogInfoService;
    @Resource
    private WalletService walletService;


    private volatile DelayQueue<UnFreezeQueueDto> delayQueue = new DelayQueue<UnFreezeQueueDto>();



    public void add(Long taskId, Long taskLogInfoId, Long cardNumberId, String requestId) {
        synchronized (this) {
            UnFreezeQueueDto unFreezeQueueDto = delayQueue.stream().filter(it -> it.getCardNumberId().equals(cardNumberId)).findFirst().orElse(null);
            if (unFreezeQueueDto == null) {
                LocalDateTime now = LocalDateTime.now();
                LocalDateTime nowB = now.plusSeconds(5L);
                long betweenMillis = ChronoUnit.MILLIS.between(now, nowB);
                log.info("当前添加的是:{},秒{}", cardNumberId, betweenMillis / 1000);
                delayQueue.put(
                        new UnFreezeQueueDto(
                                cardNumberId,
                                taskId,
                                taskLogInfoId,
                                requestId,
                                betweenMillis
                        )
                );
            }
        }
    }


    @Override
    public void run(String... args) throws Exception {
        Executors.newSingleThreadExecutor().execute(new Thread(this::excuteThread));
    }

    private void excuteThread() {
        while (true) {
            try {
                processTask(delayQueue.take());
            } catch (InterruptedException e) {
                break;
            }
        }
    }

    /**
     * 内部执行延时任务
     *
     * @param unFreezeQueueDto
     */
    private void processTask(UnFreezeQueueDto unFreezeQueueDto) {
        try {
            log.info("当前处理的卡是{}", unFreezeQueueDto.getCardNumberId());
            UserCard userCard = userCardService.getByIdOpt(unFreezeQueueDto.getCardNumberId()).orElse(null);
            if (userCard == null) {
                taskLogInfoService.completedLogInfo(unFreezeQueueDto.getTaskInfoId(), 1, "卡ID:" + unFreezeQueueDto.getCardNumberId() + "不存在");
                return;
            }
            if (userCard.getCardStatus().equals(CardStatusEnum.CONTROL.getCode())) {
                taskLogInfoService.completedLogInfo(unFreezeQueueDto.getTaskInfoId(), 2, "卡ID:" + unFreezeQueueDto.getCardNumberId() + "目前是风控状态状态无法操作");
                return;
            }
            String requestId = unFreezeQueueDto.getRequestId();
            ChannelBaseService channelBaseService = applicationContext.getBean(userCard.getChannelCode(), ChannelBaseService.class);
            CardInfoVo cardInfoVo = channelBaseService.queryCardInfo(userCard.getChannelCardId());
            if (cardInfoVo == null) {
                taskLogInfoService.completedLogInfo(unFreezeQueueDto.getTaskInfoId(), 1, "查询卡状态失败");
                return;
            }
            taskLogInfoService.setCardStatus(unFreezeQueueDto.getTaskInfoId(), cardInfoVo.getCardStatus(), cardInfoVo.getBalance());
            if (!cardInfoVo.getCardStatus().equals(CardStatusEnum.BLOCKED.getCode())) {
                taskLogInfoService.completedLogInfo(unFreezeQueueDto.getTaskInfoId(), 1, "当前卡状态不可冻结");
                return;
            }
            cardOrderService.unblockCard(
                    requestId,
                    userCard.getCardTypeId(),
                    userCard.getUserId(),
                    userCard.getUserId(),
                    userCard.getCardNumber(),
                    userCard.getId(),
                    userCard.getChannelCode(),
                    "批量解冻",
                    "CLIENT"
            );
            channelBaseService.unblockCard(userCard.getChannelCardId(), requestId);
            userCardService.updateCardStatusById(CardStatusEnum.ACTIVE.getCode(), userCard.getId());
            taskLogInfoService.completedLogInfo(unFreezeQueueDto.getTaskInfoId(), 0, "解冻成功");
        } catch (Exception e) {
            taskLogInfoService.completedLogInfo(unFreezeQueueDto.getTaskInfoId(), 1, "解冻异常:" + e.getMessage());
            log.error("异常", e);
        } finally {
            Long completeCount = taskLogInfoService.countByTaskIdAndStatus(unFreezeQueueDto.getTaskLogId(), 2);
            log.info("当前任务:{},待完成的数量是:{}", unFreezeQueueDto.getTaskLogId(), completeCount);
            if (completeCount == 0) {
                taskLogService.processedAccomplish(unFreezeQueueDto.getTaskLogId());
            }
        }
    }
}
